#include "add.h"
#include "app_config.h"  // use CMake-configured MQTT defaults
#ifndef APPCFG_DEFAULT_MQTT_HOST
#  define APPCFG_DEFAULT_MQTT_HOST "mqtt.yyzlab.com.cn"
#endif
#ifndef APPCFG_DEFAULT_MQTT_PORT
#  define APPCFG_DEFAULT_MQTT_PORT 1883
#endif
#ifndef APPCFG_DEFAULT_SUB_TOPIC
#  define APPCFG_DEFAULT_SUB_TOPIC "1756687933516/AIOTSIM2Device"
#endif
#ifndef APPCFG_DEFAULT_PUB_TOPIC
#  define APPCFG_DEFAULT_PUB_TOPIC "1756687933516/Device2AIOTSIM"
#endif
#include <stdbool.h> // 包含 stdbool.h 以使用 bool 类型

int main() {
    float temperature, humidity, guang_data;
    bool hongwai_data; // 修改为 bool 类型
    bool door_data;
    char json_data[256];

    mosquitto_lib_init();
    struct mosquitto *mosq = mosquitto_new(NULL, true, NULL);
    if (mosq == NULL) {
        printf("Error: Out of memory.\n");
        return 1;
    }

    // 注册消息回调函数
    mosquitto_message_callback_set(mosq, message_callback);

    int error = mosquitto_connect(mosq, APPCFG_DEFAULT_MQTT_HOST, APPCFG_DEFAULT_MQTT_PORT, 60);
    if (error != MOSQ_ERR_SUCCESS) {
        printf("Error: %s\n", mosquitto_strerror(error));
        return 1;
    }

    int mqtt_sub = mosquitto_subscribe(mosq, NULL, APPCFG_DEFAULT_SUB_TOPIC, 2);
    if (mqtt_sub != MOSQ_ERR_SUCCESS) {
        printf("Error: %s\n", mosquitto_strerror(mqtt_sub));
        return 1;
    }

    mosquitto_loop_start(mosq);
    while (1) {
        // 获取温湿度数据
        temperature = read_and_calculate_temperature();
        humidity = read_and_calculate_humidity();
        guang_data = read_and_calculate_guang();
        hongwai_data = detect_motion(); // 获取红外传感器数据
        door_data = key_motion();
        //control_fan(temperature);
        // 构造 JSON 数据
        /*snprintf(json_data, sizeof(json_data), 
                 "{\"tem\":%.2f,\"hum\":%.2f,\"light\":%.2f,\"infrared\":%s,\"id\":0}", 
                 temperature, humidity, guang_data, hongwai_data ? "true" : "false");*/
                 snprintf(json_data, sizeof(json_data), 
                 "{\"tem\":%.2f,\"hum\":%.2f,\"light\":%.2f,\"infrared\":%s,\"doorLock\":%s,\"id\":0}", 
                 temperature, humidity, guang_data, hongwai_data ? "true" : "false", door_data ? "true" : "false");

        // 发布数据
        publish_data(APPCFG_DEFAULT_MQTT_HOST, APPCFG_DEFAULT_PUB_TOPIC, json_data);

        // 等待一段时间
        sleep(1);
    }

    mosquitto_loop_stop(mosq, true);
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();
    return 0;
}
